/*
 * @Description: 档案管理权限规则 - 创建规则弹窗 上下文
 * @Author: Rfan
 * @Date: 2022-04-06 13:13:27
 * @LastEditTime: 2022-04-07 11:13:54
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { AddRuleReducer } from '../reducers/AddRuleReducer';
import {
  ADD_CONDITION_ITEM,
  CLEAR_CONDITION_LIST,
  DELETE_LAST_CONDITION_ITEM,
  HIDE_DIALOG,
  SHOW_DIALOG
} from '../constants';

const initialState = {
  // 弹窗显示状态
  visible: false,
  // 字段列表
  fieldList: [],
  // 条件列表
  conditionList: []
};

const AddRuleContext = createContext();

const AddRuleContextProvider = (props) => {
  const [state, dispatch] = useReducer(AddRuleReducer, initialState);

  const actions = {
    /**
     * @description: 打开弹窗
     */
    showDialog() {
      dispatch({ type: SHOW_DIALOG });
    },

    /**
     * @description: 关闭弹窗
     */
    hideDialog() {
      dispatch({ type: HIDE_DIALOG });
    },

    /**
     * @description: 添加条件条目
     * @param {*} 要添加的条目
     */
    addConditionItem(data) {
      data.id = uuidv4();
      dispatch({ type: ADD_CONDITION_ITEM, data });
    },
    /**
     * @description: 删除最后一条条目
     */
    deleteLastConditionItem() {
      dispatch({ type: DELETE_LAST_CONDITION_ITEM });
    },

    /**
     * @description: 清空所有条件
     */
    clearConditionList() {
      dispatch({ type: CLEAR_CONDITION_LIST });
    }
  };

  // watch选中的单位来加载全宗
  useEffect(() => {}, []);

  return (
    <AddRuleContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </AddRuleContext.Provider>
  );
};

export const useAddRuleContext = () => {
  return useContext(AddRuleContext);
};

export { AddRuleContext, AddRuleContextProvider };
